package org.hs.phd.common.simpleplayer.framesource;

import org.hs.phd.common.simpleplayer.FrameSource;
import org.hs.phd.common.simpleplayer.ImageSequenceFrame;

import com.googlecode.javacv.cpp.opencv_core.IplImage;
import com.googlecode.javacv.cpp.opencv_highgui;

public class FolderFrameSource implements FrameSource{
	
	
	private final String filePathPrefix;
	private final String suffix;
	private int currentFrameNo;
	private final int startFrameNo;
	private final float fps;

	public FolderFrameSource( String filePathPrefix, String suffix, int startFrameNo, float fps){
		this.filePathPrefix = filePathPrefix;
		this.suffix = suffix;
		this.startFrameNo = startFrameNo;
		this.fps = fps;
		currentFrameNo = startFrameNo;
		
	}
	
	@Override
	public ImageSequenceFrame loadNextFrame(){
		currentFrameNo++;
		return loadCurrentFrame();
	}

	@Override
	public ImageSequenceFrame loadPreviousFrame() {
		currentFrameNo--;
		return loadCurrentFrame();
	}


	private ImageSequenceFrame loadCurrentFrame() {
		
		String currentImageFileName = filePathPrefix + currentFrameNo + suffix;
		
		IplImage readImage = opencv_highgui.cvLoadImage(currentImageFileName);

		if( readImage == null ) throw new EndOfFrameSourceException( currentImageFileName + "not found!" );
		
		return new DefaultImageSequenceFrameImpl( currentFrameNo, readImage);
	}

	@Override
	public void reset() {
		currentFrameNo = startFrameNo;
	}

	@Override
	public float getFPS() {
		return fps;
	}

}
